package me.pinion.controller;

import me.pinion.Log;
import me.pinion.check.annotation.AllowRole;
import me.pinion.controller.annotation.RouteBind;
import me.pinion.model.Like;
import me.pinion.model.ModelType;
import me.pinion.model.User;
import me.pinion.model.XModel;
import me.pinion.service.LikeService;

import javax.servlet.http.HttpServletResponse;

@RouteBind("/like")
public class LikeController extends Controller{

    LikeService likeService;

    @AllowRole(["USER"])
    public void index(){
        String clazzStr = getPara("clazz");
        int targetId = getParaToInt("id");
        try {
            XModel model = ModelType.dao.getByClass(clazzStr).getModel(targetId);
            if (model == null){
                throw new NotFoundException();
            }
            Like like = likeService.like(model, this.<User>getSessionAttr("user"));
            renderJson(like);
        } catch (Exception e) {
            Log.e(e);
            e.printStackTrace()
            renderError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @AllowRole(["user"])
    public void undo(){
        XModel model = ModelType.dao.getModel(getPara("clazz"), getParaToInt("id"));
        Like like = likeService.like(model, this.<User>getSessionAttr("user"));
        like.delete();
        renderJson();
    }


}
